package implementation.sort;

import anaydis.sort.Sorter;
import anaydis.sort.SorterType;
import anaydis.sort.gui.ObservableSorter;
import anaydis.sort.gui.SorterListener;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;


public abstract class AbstractSorter<T> implements Sorter, ObservableSorter {

    private SorterType type;
    protected List<SorterListener> sorterListeners;

    protected AbstractSorter(SorterType type) {
        this.type = type;
        sorterListeners = new ArrayList<SorterListener>();
    }

    protected <T> boolean greater(Comparator<T> c, List<T> list, int i, int j) {
        for (int k = 0; k < sorterListeners.size(); k++) {
            sorterListeners.get(k).greater(i, j);
        }
        return c.compare(list.get(i), list.get(j)) > 0;
    }

    protected <T> boolean equals(Comparator<T> c, List<T> list, int i, int j) {
        for (int k = 0; k < sorterListeners.size(); k++) {
            sorterListeners.get(k).equals(i, j);
        }
        return c.compare(list.get(i), list.get(j)) == 0;
    }

    public void swap(List<T> list, int i, int j) {
        T aux = list.get(i);
        list.add(i, list.get(j));
        list.remove(i + 1);
        list.add(j, aux);
        list.remove(j + 1);
        for (int k = 0; k < sorterListeners.size(); k++) {
            sorterListeners.get(k).swap(i, j);
        }
    }

    public SorterType getType() {
        return type;
    }

    public void addSorterListener(@org.jetbrains.annotations.NotNull anaydis.sort.gui.SorterListener sorterListener) {
        sorterListeners.add(sorterListener);
    }

    public void removeSorterListener(@org.jetbrains.annotations.NotNull anaydis.sort.gui.SorterListener sorterListener) {
        sorterListeners.remove(sorterListener);
    }
}
